<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :visible.sync="dialogVisible"
    append-to-body
    width="1000px">
    <el-form
      :model="dataForm"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      :rules="rules"
      label-width="80px">
      <el-row :gutter="20">
        <el-row v-if="!this.dataForm.id">
          <el-col :span="8">
            <el-form-item v-if="!this.dataForm.id" label="人员" prop="userId">
              <el-select
                style="width:100%"
                v-model="dataForm.userId"
                filterable
                remote
                clearable
                placeholder="请输入姓名"
                :remote-method="searchUser"
                :loading="loading"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.realname + ' | ' + item.identityCard"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="处罚等级" prop="punishLevel">
              <el-select v-model="dataForm.punishLevel" filterable clearable placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in punishLevelList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="违章时间" prop="breakRuleTime">
              <el-date-picker
                  v-model="dataForm.breakRuleTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="违章原因" prop="reason">
              <el-input :rows="3" type="textarea" v-model="dataForm.reason"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="处罚结果" prop="punishResult">
              <el-input type="textarea" v-model="dataForm.punishResult"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="违反规则" prop="breakRule">
              <el-input type="textarea" v-model="dataForm.breakRule"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="关联课程">
            <el-button type="small" @click="addCourse">新增课程列表</el-button>
            <template v-if="dataList">
              <el-table
                :data="dataList"
                border
                height="250px"
              >
                <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
                <el-table-column label="课程名称" prop="title"  align="center"></el-table-column>
                <el-table-column label="分类名称" prop="cateName"  align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" @click="remove(scope.row.courseId)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="关联考试">
            <el-button type="small" @click="addExam">新增考试列表</el-button>
            <template v-if="dataexamList">
              <el-table
                :data="dataexamList"
                border
                height="250px"
              >
                <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
                <el-table-column label="考试名称" prop="examName"  align="center"></el-table-column>
                <el-table-column label="分类名称" prop="cateName"  align="center"></el-table-column>
                <el-table-column label="开始时间" prop="startTime"  align="center"></el-table-column>
                <el-table-column label="结束时间" prop="endTime"  align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" @click="removeExam(scope.row.examId)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-form-item>
        </el-row>
      </el-row>
      <el-row :gutter="20" style="display: flex">
        <el-col>
          <el-form-item prop="punishNoticeUrl" label="处罚通知书">
            <avatar-uploader
              :avatar="dataForm.punishNoticeUrl"
              title="我的头像"
              @uploaded="headerUploaded"
              :size="120"
            ></avatar-uploader>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item prop="trainNoticeUrl" label="培训通知书">
            <avatar-uploader
              :avatar="dataForm.trainNoticeUrl"
              title="培训通知书"
              @uploaded="headerUploadedtrain"
              :size="120"
            ></avatar-uploader>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item prop="remorseLetterUrl" label="检查书">
          <avatar-uploader
            :avatar="dataForm.remorseLetterUrl"
            title="我的头像"
            @uploaded="headerUploadedremo"
            :size="120"
          ></avatar-uploader>
        </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </div>

    <course-plugin ref="coursePlugin" :set-course-list="setCourseList"></course-plugin>
    <exam-plugin ref="examPlugin" :set-exam-list="setExamList"></exam-plugin>
  </el-dialog>
</template>

<script>
  // import UserAddViolations from './user-add-violations'
  import AvatarUploader from '../../../../components/uploader/avatar-uploader'
  import CoursePlugin from './course-plugin'
  import ExamPlugin from './exam-plugin'

  export default {
    name: 'user-detail-violations',
    components: {CoursePlugin, AvatarUploader, ExamPlugin},
    data() {
      return {
        dialogVisible: false,
        loading: false,
        userList: [],
        userOptions: [],
        dataList: [],
        punishLevelList: [],
        checkExamList: [],
        dataexamList: [],
        userId: '',
        dataForm: {
          id: '',
          userId: '',
          reason: '',
          punishResult: '',
          breakRule: '',
          breakRuleTime: '',
          punishLevel: '',
          remorseLetterUrl: '', // 检查
          punishNoticeUrl: '',  // 处罚
          trainNoticeUrl: '' // 培训
        },
        rules: {
          userId: [{required: true, message: '姓名不能为空', trigger: 'blur'}],
          cateId: [
            {required: true, message: '请选择课程分类', trigger: 'change'}
          ],
          reason: [{required: true, message: '违章原因不能为空', trigger: 'change'}],
          breakRule: [{required: true, message: '违反规则不能为空', trigger: 'change'}],
          breakRuleTime: [{required: true, message: '违章时间不能为空', trigger: 'change'}],
          punishResult: [{required: true, message: '处罚结果不能为空', trigger: 'change'}],
          punishLevel: [{required: true, message: '违章等级不能为空', trigger: 'change'}]
        }
      }
    },
    methods: {
      init(id) {
        this.dataForm.id = id
        this.dialogVisible = true
        this.dataList = []
        this.dataexamList = []
        if (id) {
          this.detail()
        } else {
          this.dataForm.userId = ''
        }
        this.$nextTick(async () => {
          this.$refs['dataForm'].resetFields()
        })
        this.loadPunishLevelList()
      },
      open(userId) {
        this.dataForm.userId = userId
        this.dialogVisible = true
        this.dataList = []
        this.dataexamList = []
        this.$nextTick(async () => {
          this.$refs.dataForm.resetFields()
        })
        this.loadPunishLevelList()
      },
      async loadPunishLevelList() {
        let res = await this.$http({
          method: 'post',
          url: this.$http.adornUrl('/usercenter-admin/dict/type'),
          data: { type: 'PUNISH' }
        })
        this.punishLevelList = res.data
      },
      addCourse() {
        if (this.dataForm.userId === '') {
          this.$notify.error({ title: '错误', message: '请先输入姓名' })
          return false
        }
        this.$nextTick(() => {
          this.$refs.coursePlugin.open(this.dataForm.userId, this.dataList, this.dataForm.id)
        })
      },
      addExam() {
        if (this.dataForm.userId === '') {
          this.$notify.error({ title: '错误', message: '请先输入姓名' })
          return false
        }
        this.$nextTick(() => {
          this.$refs.examPlugin.open(this.dataForm.userId, this.dataexamList, this.dataForm.id)
        })
      },
      async searchUser(keyword) {
        if (keyword !== '') {
          this.loading = true
          setTimeout(async () => {
            this.loading = false
            var userList = await this.getSearchUserList()
            this.userOptions = userList.filter(
              x => x.realname.indexOf(keyword) > -1
            )
          }, 200)
        }
      },
      // 移除
      remove(id) {
        if (this.dataForm.id) {
          this.removeCourse(id)
        } else {
          let index = this.dataList.findIndex(x => x.id === id)
          this.dataList.splice(index, 1)
        }
      },
      // 课程移除
      async removeCourse(id) {
        var confirm = await this.$confirm(`确定要进行删除操作吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        if (confirm !== 'confirm') return
        let res = await this.$http({
          url: '/usercenter-admin/breakRule/delCourse',
          method: 'post',
          data: {
            'courseId': id,
            'userId': this.dataForm.userId,
            'breakRuleId': this.dataForm.id
          }
        })
        if (res.code === 200) {
          this.$notify.success({ title: '成功', message: '移除成功' })
          this.detail()
        }
      },
      // 考试移除
      removeExam(id) {
        if (this.dataForm.id) {
          this.removeExams(id)
        } else {
          let index = this.dataexamList.findIndex(x => x.id === id)
          this.dataexamList.splice(index, 1)
        }
      },
      // 考试移除
      async removeExams(id) {
        var confirm = await this.$confirm(`确定要进行删除操作吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        if (confirm !== 'confirm') return
        let res = await this.$http({
          url: '/usercenter-admin/breakRule/delExam',
          method: 'post',
          data: {
            'examId': id,
            'userId': this.dataForm.userId,
            'breakRuleId': this.dataForm.id
          }
        })
        if (res.code === 200) {
          this.$notify.success({ title: '成功', message: '移除成功' })
          this.detail()
        }
      },
      // 每页数
      sizeChangeHandle(val) {
        this.dataForm.limit = val
        this.dataForm.page = 1
      },
      delectCate() {
        this.current = { name: '', id: '' }
        this.cateId = ''
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.dataForm.page = val
      },
      setCourseList(data) {
        console.log(data)
        this.dataList = data
      },
      setExamList(data) {
        console.log(data)
        this.dataexamList = data
      },
      async getSearchUserList() {
        if (this.userList.length === 0) {
          var url = '/usercenter-admin/user/getSimpleUserInfoList'
          let result = await this.$http.post(url)
          this.userList = result.data
        }
        return this.userList
      },
      async detail() {
        let res = await this.$http({
          url: this.$http.adornUrl(`/usercenter-admin/breakRule/info/${this.dataForm.id}`),
          method: 'post'
        })
        this.dataForm = res.data
        this.dataList = res.data.breakRuleCourseList
        this.dataexamList = res.data.breakRuleExamList
      },
      async exam() {
        let res = await this.$http({
          url: this.$http.adornUrl(`/usercenter-admin/breakRule/info/`),
          method: 'post'
        })
        console.log(res)
      },
      parameter () {
        return {
          id: this.dataForm.id,
          userId: this.dataForm.userId,
          reason: this.dataForm.reason,
          punishResult: this.dataForm.punishResult,
          breakRule: this.dataForm.breakRule,
          breakRuleTime: this.dataForm.breakRuleTime,
          punishLevel: this.dataForm.punishLevel,
          remorseLetterUrl: this.dataForm.remorseLetterUrl,
          punishNoticeUrl: this.dataForm.punishNoticeUrl,
          trainNoticeUrl: this.dataForm.trainNoticeUrl,
          courseIds: this.dataList ? this.dataList.map(x => x.id).join(',') : [],
          examIds: this.dataexamList ? this.dataexamList.map(x => x.id).join(',') : []
        }
      },
      // 处罚
      headerUploaded(file) {
        this.dataForm.punishNoticeUrl = file.url
      },
      // 培训
      headerUploadedtrain(file) {
        this.dataForm.trainNoticeUrl = file.url
      },
      // 检查
      headerUploadedremo(file) {
        this.dataForm.remorseLetterUrl = file.url
      },
      // 确定
      async dataFormSubmit() {
        try {
          let isValid = await this.$refs['dataForm'].validate()
          if (!isValid) return
          this.loading = true
          let res = await this.$http({
            url: this.$http.adornUrl(`/usercenter-admin/breakRule/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.parameter()
          })

          if (res && res.code === 200) {
            this.dialogVisible = false
            this.$notify.success({ title: '成功', message: '保存成功' })
            this.$emit('refreshDataList')
            this.$refs.ckEditor && this.$refs.ckEditor.setData('')
          } else {
            this.$notify.error({ title: '错误', message: res.msg })
          }
          this.loading = false
        } catch (err) {
          this.loading = false
        }
      }
    }
  }
</script>

<style scoped>
  .body {
    height: 300px;
    border: 1px solid #CCCCCC;
    margin: 20px;
    font-size: 18px;
    padding: 20px;
  }

  .row {
    margin-bottom: 20px;
  }

  .text {
    color: #c3c3c3;
  }

  .box {
    width: 500px;
    height: 400px;
    border: 1px solid #CCCCCC;
    margin: 20px;
    font-size: 20px;
    padding-top: 10px;
    text-align: center;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 300 pxx;
    height: 300px;
    display: block;
  }
</style>
